package com.eco.fanliapp.job.dtkitemjob;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.dao.AppGoodsMapper;
import com.eco.fanliapp.dataoke.DaTaoKeItemInfoService;
import com.eco.fanliapp.entity.AppCompany;
import com.eco.fanliapp.entity.AppGoods;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.DateUtils;
import com.eco.fanliapp.utils.JsonUtils;
import com.eco.fanliapp.vo.respone.DTKResponse;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

/**
 * 全量获取大淘客商品列表
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class DTKItemTask implements Job, Serializable {
    private static final Logger log = LoggerFactory.getLogger(DTKItemTask.class);

    @Autowired
    private IAppGoodsService iAppGoodsService;
    @Autowired
    private IUserCashschemeService userCashschemeService;
    @Autowired
    private DaTaoKeItemInfoService daTaoKeItemInfoService;
    @Autowired
    private AppGoodsMapper appGoodsMapper;


    public DTKItemTask() {
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long beginTime = System.currentTimeMillis();
        log.info("***************************************开始执行获取大淘客商品列表定时任务-DTKItemTask：executeCount=" + executeCount + "--beginTime=" + beginTime);

        long startTime = System.currentTimeMillis();
        String pageId = "1";
        String pageSize = "200";
        while (true) {
            try {
                String result = daTaoKeItemInfoService.getGoodsList(pageSize, pageId);
                result = JSONObject.parseObject(result).getString("data");
                String pageid = JSONObject.parseObject(result).getString("pageId");
                JSONArray array = JSONArray.parseArray(JSONObject.parseObject(result).getString("list"));
                List<DTKResponse.DataBean> dtkResponse = JsonUtils.getJsonToList(array.toJSONString(), DTKResponse.DataBean.class);
                if (dtkResponse == null || dtkResponse.size() <= 0) {
                    break;
                }
                AppCompany com = userCashschemeService.findCompanyAll();
                for (DTKResponse.DataBean dataBean : dtkResponse) {

//                    if (dataBean != null) {
                        AppGoods goods = HDKUtils.getAppGoodsFromDTK(dataBean);
                        goods = iAppGoodsService.getMoneyInfoByGoodsId(com, goods);
                        //判断是否最终金额小于0
                        BigDecimal itemendprice = new BigDecimal(goods.getItemendprice() == null ? 0d : goods.getItemendprice());
                        BigDecimal tkMoney = new BigDecimal(goods.getTkmoney() == null ? "0" : goods.getTkmoney());
                        if ((itemendprice.subtract(tkMoney)).compareTo(new BigDecimal(0)) < 0) {
                            continue;
                        }
                        goods.setTaobaoImage(goods.getTaobaoImage() == null ? goods.getItempic() : goods.getTaobaoImage().replace(" ", ""));
                        goods.setCreateTime(DateUtils.getNowTimestamp());
                        goods.setUpdateTime(DateUtils.getNowTimestamp());
                        goods.setAddUserId(-114);
                        //根据商品id查询商品是否存在
                        Integer num = appGoodsMapper.selectAppGoodsByAddUserId(goods.getItemid());
                        if (num > 0) {
                            continue;
                        }
                        Integer appGoodsNum = appGoodsMapper.selectCountByItemId(goods.getItemid());
                        if (appGoodsNum > 0) {
                            int i = appGoodsMapper.updateAppGoodsByItemId(goods);
                            if (i > 0) {
                                //更新商品
//                                iAppGoodsService.updateIndex(goods, "update");

                            }
                        } else {
                            int i = appGoodsMapper.insertAppGoods(goods);
                            if (i > 0) {
                                //添加索引
//                                iAppGoodsService.updateIndex(goods, "add");
                                log.info("添加商品成功   获取大淘客商品列表");
                            }
                        }
//                    } else {
//                        break;
//                    }
                }
                pageId = pageid;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取大淘客商品列表错误");
                break;
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行获取大淘客商品列表定时任务任务-DTKItemTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }
}
